from flask_app.app_utils import get_uuid
from flask_app.extensions import db
from ...app_exception import SQLOperationError


class RoleMD(db.Model):
    __tablename__ = "role_t"
    # 角色唯一标识
    id = db.Column(db.String(80), primary_key=True)

    # 角色名
    name = db.Column(db.String(80))

    # 角色类型
    role_type = db.Column(db.String(80))

    # 父角色id
    parent_id = db.Column(db.String(80))

    def __init__(self, role_name=None, role_type=None, parent_id=None):
        """
        初始化类
        获取角色，如果id为None则视为创建一个，否则按id返回一个
        Args:
            role_name: 角色名
            parent_id: 父节点id
            role_type: 角色类型
        Returns:
            角色类RoleMD
        """
        self.id = get_uuid()
        self.name = role_name
        self.parent_id = parent_id
        self.role_type = role_type

    def delete(self, fource_del=0):
        """
        删除角色
        Args:
            fource_del: 0 为默认，不做强制删除
                        1 为强制删除

        Returns:
            False，msg 删除失败，msg为错误信息
            True，msg  删除成功，msg为正确信息
        """
        children = self.get_all_child_role()
        if len(children) > 0 and fource_del == 0:
            return False, "此角色存在子节点，需确认强制删除！"

        # 删除子节点
        try:
            children_id = [child.id for child in children]
            RoleMD.query.filter(RoleMD.id.in_(children_id)).delete(synchronize_session=False)
            db.session.delete(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise SQLOperationError("从数据库删除角色失败，已回滚！/n" + str(e))
        return True, "删除成功！"

    @staticmethod
    def get(role_id):
        return RoleMD.query.get(role_id)

    @staticmethod
    def add(obj):
        """
        添加角色
        Returns:

        """
        try:
            db.session.add(obj)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise SQLOperationError("向数据库插入角色失败，已回滚！/n" + str(e))
        return True, "保存成功！"

    def update(self):
        '''
        更新当前角色
        Returns:

        '''
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise SQLOperationError("向数据库更新角色失败，已回滚！/n" + str(e))
        return True, "保存成功！"

    def get_parent_role(self):
        """
        获取角色的父节点
        Returns:
            父节点角色类RoleMD
        """

        if self.parent_id == None:
            return None
        else:
            return RoleMD(id=self.parent_id)

    def get_all_child_role(self):
        """
        返回所有的子角色节点
        Returns:
        所有的子节点
        """
        children = [role for role in RoleMD.query.filter_by(parent_id=self.id)]
        grandchildren = []
        if len(children) == 0:
            return children
        else:
            for child in children:
                grandchildren.extend(child.get_all_child_role())
            children.extend(grandchildren)
            return children

    def __str__(self):
        return self.name
